<script lang="ts">
import {defineComponent, onMounted, reactive, ref, computed, h, defineAsyncComponent} from "vue"
import LibraryConfig, {ResourceLibraryType, ComponentData, ConfigType} from "./config";
import type {PropType} from 'vue';
import Cate from "./Cate.vue"
import {getResourcesListApi, getUploaderConfigureApi, renameResourcesApi} from "@/api/resources";
import {Ref, UnwrapRef} from "@vue/reactivity";
import {useCloseMessageBox} from "@/hooks/DialogMsg"
import {usePopupComponent} from "@/components/FunctionComponents";
import {ElMessage, ElMessageBox} from "element-plus";

export default defineComponent({
  props: {
    type: {
      type: String as PropType<ResourceLibraryType>,
      required: true
    },
    limit: {type: Number, default: 15}
  },
  emits: {
    choice: (res: any[]) => true
  },
  components: {...ComponentData(), Cate},
  setup(props, {emit}) {
    /**
     * 资源分类
     */
    const classify = ref<{ id: number, name: string }[]>([])

    /**
     * 搜索条件
     */
    const where = ref({
      cate_id: 0,
      name: ''
    })

    const CloseFunction = useCloseMessageBox()

    //资源库配置
    const config: ConfigType = LibraryConfig[props.type];

    /**
     * 请求数据
     */
    const ResData = reactive({
      list: [],
      page: 1,
      size: config.limit,
      total: 0,
      loading: false
    })

    /**
     * 选中资源
     */
    const active: Ref<UnwrapRef<Array<any>>> = ref([])

    /**
     * 选中资源回调
     * @constructor
     */
    function ActiveEvent(res: any) {
      let newActive = []
      let add: boolean = true
      for (let item of active.value) {
        if (item.id === res.id) {
          add = false
          continue;
        }
        newActive.push(item)
      }
      if (add) {
        newActive.push(res)
      }
      active.value = newActive.splice(0 - props.limit)
    }

    /**
     * 选中资源ID值
     */
    const activeId = computed(() => {
      return active.value.map(item => item.id)
    })


    /**
     * 获取资源库资源
     */
    async function getResourceLibraryData(query: { [key: string]: any }) {
      if (ResData.loading === true) return;
      ResData.loading = true
      let {code, data} = await getResourcesListApi({...query, ...where.value})
      if (code === 200) {
        ResData.list = data.list
        ResData.total = data.total
        ResData.page = data.current
      }
      ResData.loading = false
    }


    /**
     * 打开上传
     */
    function openUpload() {
      getUploaderConfigureApi(props.type).then(result => {
        const component: any = h(defineAsyncComponent((): any => import("./Upload/ChoiceResource.vue")), {
          type: props.type,
          conf: config,
          classify: classify.value,
          uploadConf: result.data,
          onClose: () => {
            getResourceLibraryData({type: props.type, size: config.limit, page: ResData.page})
          }
        })
        usePopupComponent(`上传${config.name}`, component, "680px")
      })
    }

    /**
     * 使用资源
     */
    function useRes() {
      emit('choice', active.value)
      CloseFunction()
    }

    /**
     * 分页组件
     * @constructor
     */
    function ResPagination(page_number: number, size_number: number) {
      getResourceLibraryData({type: props.type, size: config.limit, page: page_number})
    }

    /**
     * 文件重命名
     */
    function resResname(res: any) {
      ElMessageBox.prompt('请输入新的资源名称', '资源重命名', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputValue: res.name,
        inputPattern: /^[\S]{1,40}$/,
        inputErrorMessage: '请输入1-40个字的新名称，不能含有空白字符',
      }).then(({value}) => {
        if (value === res.name) {
          ElMessage({type: "success", message: '资源名称已修改'})
        } else {
          renameResourcesApi({id: res.id, name: value}).then(res => {
            if (res.code === 200) {
              ElMessage({type: "success", message: '资源名称已修改'})
              getResourceLibraryData({type: props.type, size: config.limit, page: ResData.page})
            }
          })
        }
      }).catch(() => {
        ElMessage({type: "info", message: '操作已取消'})
      })
    }


    /**
     * 分类切换
     * @param cid
     */
    function CateChange(cid: number) {
      where.value.cate_id = cid
      getResourceLibraryData({type: props.type, size: config.limit, page: 1})
    }

    /**
     * 分类数据刷新了
     */
    function classifyChange(data: { id: number, name: string }[]) {
      classify.value = data
    }

    /**
     * 加载完毕获取数据
     */
    onMounted(() => {
      getResourceLibraryData({type: props.type, size: config.limit, page: 1})
    })

    return {
      ResData, ActiveEvent, activeId, config, CloseFunction, active, openUpload, useRes, ResPagination, resResname, where, CateChange, getResourceLibraryData, classifyChange
    }
  }
})
</script>
<template>
  <div class="resource-library">
    <el-page-header>
      <template #content>
        <div>{{ config.name }}库</div>
      </template>
      <template #extra>
        <el-space size="small">
          <el-input maxlength="20" v-model.trim="where.name" placeholder="请输入资源名称">
            <template #suffix>
              <el-link @click="getResourceLibraryData({type:type, size: config.limit, page: 1})" :underline="false" type="primary">搜索</el-link>
            </template>
          </el-input>
          <el-button @click="openUpload" color="#835fc9">上传</el-button>
          <template v-if="activeId.length">
            <el-button type="primary" @click="useRes">
              使用({{ activeId.length }})
            </el-button>
            <el-button @click="active=[]" type="warning">
              取消
            </el-button>
          </template>
          <template v-else>
            <el-button @click="CloseFunction" type="danger">
              关闭
            </el-button>
          </template>
        </el-space>
      </template>
    </el-page-header>
    <el-container class="app-margin-top-medium">
      <el-aside>
        <cate :cate_id="where.cate_id" :type="type" @change="CateChange" @classify="classifyChange"></cate>
      </el-aside>
      <el-main>
        <component @active="ActiveEvent" :active="activeId" @rename="resResname" :data="ResData.list" :is="`${type}-list`"></component>
      </el-main>
    </el-container>
  </div>
  <div class="app-margin-top-medium">
    <app-pagination layout="prev, pager, next" @change="ResPagination" :disabled="ResData.loading" :total="ResData.total" :size="ResData.size" :page="ResData.page"></app-pagination>
  </div>
</template>

<style scoped lang="scss">
.resource-library {
  margin: 0;
  padding: 0;

  .el-page-header {
    .el-page-header__left {
      .el-page-header__back {
        display: none;
      }
    }
  }

  :deep(.el-container) {
    border: 1px solid var(--el-border-color);

    .el-aside {
      width: 188px !important;
      margin-right: 2px;
      border-right: 1px solid var(--el-border-color);
      box-shadow: none;
      padding: 0;
      height: 380px;
      overflow-y: scroll;
      -ms-overflow-style: none; /* IE and Edge */
      scrollbar-width: none; /* Firefox */
      &::-webkit-scrollbar {
        display: none;
      }

      .el-menu {
        height: 100%;
      }
    }

    .el-main {
      height: 380px;
      padding: 0;
      overflow-y: scroll;
      -ms-overflow-style: none; /* IE and Edge */
      scrollbar-width: none; /* Firefox */
      &::-webkit-scrollbar {
        display: none;
      }
    }
  }
}
</style>